package org.linlinjava.litemall.admin.service.order_manage;

import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.core.rabbitmq.DirectExchangeProducer;
import cn.com.ejiakanghu.dto.PackageDto;
import cn.ejiakanghu.logistics.service.impl.LogisticBusiBaseServiceImpl;
import cn.ejiakanghu.logistics.service.impl.LogisticsBaseServiceAbstractImpl;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.checkerframework.checker.units.qual.A;
import org.linlinjava.litemall.admin.vo.order_manage.*;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallShopMapper;
import org.linlinjava.litemall.db.dao.order_manage.BackendAfterSaleMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.*;
import org.linlinjava.litemall.db.service.AgedmallAnnouncerBaseInfoService;
import org.linlinjava.litemall.db.service.AgedmallGoodsShipTypeService;
import org.linlinjava.litemall.db.service.AgedmallOrderLogisticsService;
import org.linlinjava.litemall.db.service.AgedmallProcessStateService;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.app.AgedmallGoodsShipTypeVo;
import org.linlinjava.litemall.db.vo.order_manage.BackendAfterSalePickupVo;
import org.linlinjava.litemall.db.vo.order_manage.BackendAfterSaleVo;
import org.linlinjava.litemall.db.vo.wechat.SeparateWechatData;
import org.linlinjava.litemall.db.vo.wechat.ToLitemallBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AgedmallOrderAfterSaleService {

    @Resource
    private LitemallAftersaleMapper litemallAftersaleMapper;
    @Resource
    private BackendAfterSaleMapper backendAfterSaleMapper;
    @Resource
    private AgedmallReturnGoodsRecordMapper agedmallReturnGoodsRecordMapper;
    @Resource
    private LitemallAftersaleRemarkMapper litemallAftersaleRemarkMapper;
    @Resource
    private LitemallUserMapper litemallUserMapper;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Autowired
    private AgedmallGoodsShipTypeService agedmallGoodsShipTypeService;
    @Resource
    private LitemallGoodsMapper litemallGoodsMapper;
    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private AgedmallProcessStateService agedmallProcessStateService;
    @Resource
    private AgedmallPrintOrderMapper agedmallPrintOrderMapper;
    @Resource
    private AgedmallShopMapper agedmallShopMapper;
    @Resource
    private DirectExchangeProducer directExchangeProducer;
    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;
    @Resource
    private LogisticsGoodsUtil logisticsGoodsUtil;
    @Resource
    private AgedmallCloudHouseMapper agedmallCloudHouseMapper;
    @Resource
    private AgedmallAnnouncerBaseInfoService agedmallAnnouncerBaseInfoService;
    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;
    @Resource
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;


    public Object orderList(Integer searchType, String searchValue, Integer state, Integer provinceId, Integer cityId, Integer storeId,
                            LocalDateTime startTime, LocalDateTime endTime, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        List<Integer> states = AftersaleConstant.front2back(state);
        List<BackendAfterSaleVo> list = backendAfterSaleMapper.orderList(searchType, searchValue, states, provinceId, cityId, storeId, startTime, endTime);
        list.stream().forEach(p ->{
            List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(p.getGoodsSpec(), LitemallGoodsProductSpecification.class);
            String spec = "";
            if (CollectionUtils.isNotEmpty(specificationList)) {
                for (LitemallGoodsProductSpecification specification : specificationList) {
                    spec += "," + specification.getInfoName() + ":" + specification.getName();
                }
            }
            p.setGoodsSpec(spec.replaceFirst(",", ""));
            p.setAfterSaleState(AftersaleConstant.back2front(p.getAfterSaleState()));
        });
        return ResponseUtil.okList(list);
    }

    public Object button(Integer id, Integer state, BigDecimal amount, String reason){
        LitemallAftersale litemallAftersale = litemallAftersaleMapper.selectByPrimaryKey(id);
        if (null == litemallAftersale) {
            return ResponseUtil.badArgumentValue();
        }
        // 拒绝
        if (0 == state) {
            litemallAftersale.setStatus(AftersaleConstant.STATUS_REJECT);
            litemallAftersale.setHandleTime(LocalDateTime.now());
            litemallAftersale.setRejectReason(reason);
            litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
        // 同意
        } else if (1 == state) {
            // 仅退款 同意直接退款
            if (AftersaleConstant.TYPE_GOODS_MISS.equals(litemallAftersale.getType())) {
                litemallAftersale.setStatus(AftersaleConstant.STATUS_REFUND);
                litemallAftersale.setHandleTime(LocalDateTime.now());
                litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
                // todo sunj 退款
            // 退货 同意后，待用户自行寄回
            } else if (AftersaleConstant.TYPE_GOODS_NEEDLESS.equals(litemallAftersale.getType())) {
                litemallAftersale.setStatus(AftersaleConstant.STATUS_WAIT_SEND);
                litemallAftersale.setHandleTime(LocalDateTime.now());
                litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
                // 添加售后状态
                agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, id, ProcessStateConstant.AFTERSALE_STATE_SENDBACK);
            // 换货 同意后， 1上门取件，安排取件人员 2待用户寄回
            } else if (AftersaleConstant.TYPE_GOODS_REQUIRED.equals(litemallAftersale.getType())) {
                AgedmallReturnGoodsRecordExample agedmallReturnGoodsRecordExample = new AgedmallReturnGoodsRecordExample();
                agedmallReturnGoodsRecordExample.createCriteria().andDeletedEqualTo(false)
                        .andAfterSaleIdEqualTo(litemallAftersale.getId());
                AgedmallReturnGoodsRecord agedmallReturnGoodsRecord = agedmallReturnGoodsRecordMapper.selectOneByExample(agedmallReturnGoodsRecordExample);
                if (ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP.equals(agedmallReturnGoodsRecord.getGetGoodsStyle())) {
                    litemallAftersale.setStatus(AftersaleConstant.STATUS_WAIT_PICK);
                    litemallAftersale.setHandleTime(LocalDateTime.now());
                    litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
                    // 添加售后状态
                    agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, id, ProcessStateConstant.AFTERSALE_STATE_PICKUP);
                    // todo sunj 配货发货
                } else {
                    litemallAftersale.setStatus(AftersaleConstant.STATUS_WAIT_SEND);
                    litemallAftersale.setHandleTime(LocalDateTime.now());
                    litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
                    // 添加售后状态
                    agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, id, ProcessStateConstant.AFTERSALE_STATE_SENDBACK);
                }
            }
        // 修改金额
        } else if (2 == state) {
            litemallAftersale.setAmount(amount);
            litemallAftersale.setHandleTime(LocalDateTime.now());
            litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
        }
        return ResponseUtil.ok();
    }

    public Object remark(Integer id, String remark){
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        if (null == admin) {
            return ResponseUtil.unlogin();
        }
        LitemallAftersale litemallAftersale = litemallAftersaleMapper.selectByPrimaryKey(id);
        if (null == litemallAftersale) {
            return ResponseUtil.badArgumentValue();
        }
        LitemallAftersaleRemark litemallAftersaleRemark = new LitemallAftersaleRemark();
        litemallAftersaleRemark.setAftersaleId(litemallAftersale.getId());
        litemallAftersaleRemark.setRemark(remark);
        litemallAftersaleRemark.setUserId(admin.getId());
        litemallAftersaleRemark.setUserName(admin.getUsername());
        litemallAftersaleRemark.setAddTime(LocalDateTime.now());
        litemallAftersaleRemark.setDeleted(false);
        litemallAftersaleRemarkMapper.insertSelective(litemallAftersaleRemark);

        return ResponseUtil.ok();
    }

    @Transactional
    public Object receivedCommodity(Integer id, Integer commodityId){
        LitemallAftersale litemallAftersale = litemallAftersaleMapper.selectByPrimaryKey(id);
        if (null == litemallAftersale) {
            return ResponseUtil.badArgumentValue();
        }
        AgedmallReturnGoodsRecordExample agedmallReturnGoodsRecordExample = new AgedmallReturnGoodsRecordExample();
        agedmallReturnGoodsRecordExample.createCriteria().andDeletedEqualTo(false)
                .andAfterSaleIdEqualTo(litemallAftersale.getId());
        AgedmallReturnGoodsRecord agedmallReturnGoodsRecord = agedmallReturnGoodsRecordMapper.selectOneByExample(agedmallReturnGoodsRecordExample);
        // 退货，收货后退款。
        if (AftersaleConstant.TYPE_GOODS_NEEDLESS.equals(litemallAftersale.getType())) {
            agedmallReturnGoodsRecord.setEndTime(LocalDateTime.now());
            agedmallReturnGoodsRecordMapper.updateByPrimaryKey(agedmallReturnGoodsRecord);

            litemallAftersale.setStatus(AftersaleConstant.STATUS_REFUND);
            litemallAftersale.setHandleTime(LocalDateTime.now());
            litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
            // 添加售后状态
            agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, id, ProcessStateConstant.AFTERSALE_STATE_SIGN);
            // todo sunj 退款
        // 换货
        } else if (AftersaleConstant.TYPE_GOODS_REQUIRED.equals(litemallAftersale.getType())) {
            // 上门取件，收货后完成
            if (ReturnGoodsRecordConstant.GET_GOODS_STYLE_PICK_UP.equals(agedmallReturnGoodsRecord.getGetGoodsStyle())) {
                agedmallReturnGoodsRecord.setEndTime(LocalDateTime.now());
                agedmallReturnGoodsRecordMapper.updateByPrimaryKey(agedmallReturnGoodsRecord);

                litemallAftersale.setStatus(AftersaleConstant.STATUS_FINISH);
                litemallAftersale.setHandleTime(LocalDateTime.now());
                litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
                // todo sunj 配货发货
            // 自行寄回，收货后 配货发货
            } else {
                agedmallReturnGoodsRecord.setEndTime(LocalDateTime.now());
                agedmallReturnGoodsRecordMapper.updateByPrimaryKey(agedmallReturnGoodsRecord);

                litemallAftersale.setStatus(AftersaleConstant.STATUS_EXCHANGE);
                litemallAftersale.setHandleTime(LocalDateTime.now());
                litemallAftersaleMapper.updateByPrimaryKey(litemallAftersale);
            }
        }

        return ResponseUtil.ok();
    }

    public Object orderDetail(@RequestParam Integer afterSaleId){
        LitemallAftersale litemallAftersale = litemallAftersaleMapper.selectByPrimaryKey(afterSaleId);
        if (null == litemallAftersale) {
            return ResponseUtil.badArgumentValue();
        }
        LitemallOrder order = litemallOrderMapper.selectByPrimaryKey(litemallAftersale.getOrderId());
        LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectByPrimaryKey(litemallAftersale.getOrderGoodsId());
        LitemallGoods goods = litemallGoodsMapper.selectByPrimaryKey(orderGoods.getGoodsId());
        LitemallGoodsProduct product = litemallGoodsProductMapper.selectByPrimaryKey(orderGoods.getProductId());
        AgedmallReturnGoodsRecordExample agedmallReturnGoodsRecordExample = new AgedmallReturnGoodsRecordExample();
        agedmallReturnGoodsRecordExample.createCriteria().andDeletedEqualTo(false)
                .andAfterSaleIdEqualTo(litemallAftersale.getId());
        AgedmallReturnGoodsRecord agedmallReturnGoodsRecord = agedmallReturnGoodsRecordMapper.selectOneByExample(agedmallReturnGoodsRecordExample);

        AfterSaleDetailVo afterSaleDetailVo = new AfterSaleDetailVo();
        // 售后基础信息
        afterSaleDetailVo.setId(litemallAftersale.getId());
        afterSaleDetailVo.setState(AftersaleConstant.back2front(litemallAftersale.getStatus().intValue()));
        afterSaleDetailVo.setType(litemallAftersale.getType().intValue());
        afterSaleDetailVo.setGetGoodsStyle(agedmallReturnGoodsRecord.getGetGoodsStyle().intValue());
        afterSaleDetailVo.setCanShip(null == agedmallReturnGoodsRecord.getReturnTime() ? 0 : 1);
        afterSaleDetailVo.setAmount(litemallAftersale.getAmount());

        // 售后备注
        LitemallAftersaleRemarkExample litemallAftersaleRemarkExample = new LitemallAftersaleRemarkExample();
        litemallAftersaleRemarkExample.createCriteria().andDeletedEqualTo(false)
                .andAftersaleIdEqualTo(litemallAftersale.getId());
        List<LitemallAftersaleRemark> litemallAftersaleRemarks = litemallAftersaleRemarkMapper.selectByExample(litemallAftersaleRemarkExample);
        List<AfterSaleDetailRemarkVo> remarks = litemallAftersaleRemarks.stream()
                .map(p -> {
                    AfterSaleDetailRemarkVo afterSaleDetailRemarkVo = new AfterSaleDetailRemarkVo();
                    afterSaleDetailRemarkVo.setAddTime(p.getAddTime());
                    afterSaleDetailRemarkVo.setRemark(p.getRemark());
                    afterSaleDetailRemarkVo.setUserName(p.getUserName());
                    return afterSaleDetailRemarkVo;
                }).collect(Collectors.toList());
        afterSaleDetailVo.setRemarks(remarks);

        // 售后信息
        AfterSaleDetailAfterSaleVo afterSaleInfo = new AfterSaleDetailAfterSaleVo();
        afterSaleInfo.setAfterSaleSn(litemallAftersale.getAftersaleSn());
        afterSaleInfo.setApplyTime(litemallAftersale.getAddTime());
        LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(litemallAftersale.getUserId());
        if (null != litemallUser) {
            afterSaleInfo.setApplicant(litemallUser.getNickname());
            afterSaleInfo.setApplicantPhone(litemallUser.getMobile());
        }
        afterSaleInfo.setAfterSaleType(litemallAftersale.getType().intValue());
        afterSaleInfo.setRefundAmount(litemallAftersale.getAmount());
        afterSaleInfo.setRefundCount(orderGoods.getNumber().intValue());
        afterSaleInfo.setRefundReason(litemallAftersale.getReason());

        afterSaleInfo.setGoodsAmount(order.getGoodsPrice());
        afterSaleInfo.setActualAmount(order.getActualPrice());
        afterSaleInfo.setGoodsCount(orderGoods.getNumber().intValue());
        afterSaleInfo.setOrderSn(order.getOrderSn());
        AgedmallStore agedmallStore = agedmallStoreMapper.selectByPrimaryKey(order.getStoreId().longValue());
        if (null != agedmallStore) {
            afterSaleInfo.setStoreName(agedmallStore.getStoreName());
            afterSaleInfo.setStoreAddress(agedmallStore.getProvinceName() + agedmallStore.getCityName() +
                                            agedmallStore.getAreaName() + agedmallStore.getAddressDetail());
        }
        afterSaleInfo.setLogistics(getLogistics(order, orderGoods));

        afterSaleDetailVo.setAfterSaleInfo(afterSaleInfo);

        // 售后商品信息
        AfterSaleDetailGoodsVo goodsInfo = new AfterSaleDetailGoodsVo();
        goodsInfo.setGoodsName(goods.getName());
        goodsInfo.setGoodsPic(goods.getPicUrl());
        List<LitemallGoodsProductSpecification> specificationList = JSON.parseArray(product.getSpecifications(), LitemallGoodsProductSpecification.class);
        String spec = "";
        if (CollectionUtils.isNotEmpty(specificationList)) {
            for (LitemallGoodsProductSpecification specification : specificationList) {
                spec += "," + specification.getInfoName() + ":" + specification.getName();
            }
        }
        goodsInfo.setGoodsSpec(spec.replaceFirst(",", ""));
        goodsInfo.setGoodsSn(goods.getGoodsSn());
        goodsInfo.setGoodsType(goods.getGoodsType());
        goodsInfo.setGoodsCount(orderGoods.getNumber().intValue());
        goodsInfo.setFreight(getLogistics(order, orderGoods));
        goodsInfo.setDiscount("");
        goodsInfo.setTotal(litemallAftersale.getAmount());
        goodsInfo.setGoodsState(litemallAftersale.getStatus().intValue());
        afterSaleDetailVo.setGoodsInfo(goodsInfo);

        // 取货信息
        AfterSaleDetailPickupVo pickupInfo = new AfterSaleDetailPickupVo();
        pickupInfo.setPickupTime(agedmallReturnGoodsRecord.getDeliveryTime());
        pickupInfo.setGetGoodsStyle(agedmallReturnGoodsRecord.getGetGoodsStyle().intValue());
        AgedmallDeliveryManInfo agedmallDeliveryManInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(agedmallReturnGoodsRecord.getDeliveryManId());
        pickupInfo.setDeliveryMan(agedmallDeliveryManInfo.getUsername());
        pickupInfo.setHandler(litemallAftersale.getHandler());
        pickupInfo.setStorageState(null == agedmallReturnGoodsRecord.getReturnTime() ? 0 : 1);
        pickupInfo.setGoodsName(goods.getName());
        pickupInfo.setGoodsPic(goods.getPicUrl());
        pickupInfo.setGoodsSpec(product.getSpecifications());
        pickupInfo.setGoodsCount(orderGoods.getNumber().intValue());
        pickupInfo.setRfid(orderGoods.getRfid());
        afterSaleDetailVo.setPickupInfo(pickupInfo);

        // 取货状态
        List<AgedmallProcessState> processStates = agedmallProcessStateService.getList(ProcessStateConstant.TYPE_AFTERSALE, litemallAftersale.getId());
        List<AfterSaleDetailPickupStateVo> pickupStates = processStates.stream()
                .map(p -> {
                    AfterSaleDetailPickupStateVo afterSaleDetailPickupStateVo = new AfterSaleDetailPickupStateVo();
                    afterSaleDetailPickupStateVo.setState(p.getState());
                    afterSaleDetailPickupStateVo.setTime(p.getAddTime());
                    return afterSaleDetailPickupStateVo;
                }).collect(Collectors.toList());
        afterSaleDetailVo.setPickupStates(pickupStates);

        return ResponseUtil.ok(afterSaleDetailVo);
    }

    public String getLogistics(LitemallOrder order, LitemallOrderGoods orderGoods) {
        String result = null;

        List<AgedmallGoodsShipTypeVo> voList = agedmallGoodsShipTypeService.getByGoodsAndStore(AgedmallShipDictConstant.TYPE_SHIP, orderGoods.getGoodsId(), orderGoods.getStoreId());
        AgedmallGoodsShipTypeVo agedmallGoodsShipTypeVo = voList.stream()
                .filter(p -> AgedmallShipDictConstant.SHIP_SN_NORMAL.equals(p.getShipSn()))
                .findFirst().orElse(null);
        BigDecimal normalPrice = BigDecimal.ZERO;
        if (null != agedmallGoodsShipTypeVo) {
            JSONObject rule = JSONObject.parseObject(agedmallGoodsShipTypeVo.getRule());
            normalPrice = new BigDecimal(rule.getInteger("price"));
        }
        AgedmallGoodsShipTypeVo shipTypeVo = agedmallGoodsShipTypeService.getByGoodsAndStoreAndShip(AgedmallShipDictConstant.TYPE_SHIP, orderGoods.getGoodsId(), orderGoods.getStoreId(), order.getDeliverySn());
        if (AgedmallShipDictConstant.SHIP_SN_NORMAL.equals(order.getDeliverySn())) {
            String price = normalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            result = shipTypeVo.getShipName() + " ￥" + price;
        }
        if (AgedmallShipDictConstant.SHIP_SN_URGENT.equals(order.getDeliverySn())) {
            String price = normalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            TempSubOrderParamDeliveryUrgent urgent = JSONObject.parseObject(order.getDeliveryChoose(), TempSubOrderParamDeliveryUrgent.class);
            String urgentPrice = "0";
            if (null != urgent && null != urgent.getPrice()) {
                urgentPrice = urgent.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            }
            result = shipTypeVo.getShipName() + " ￥" + price+"/感谢费￥"+urgentPrice;
        }
        if (AgedmallShipDictConstant.SHIP_SN_SUBSCRIBE.equals(order.getDeliverySn())) {
            TempSubOrderParamDeliverySubscribe subscribe = JSONObject.parseObject(order.getDeliveryChoose(), TempSubOrderParamDeliverySubscribe.class);
            String subscribePrice = normalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            if (null != subscribe && null != subscribe.getPrice()) {
                subscribePrice = normalPrice.add(subscribe.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            }
            result = shipTypeVo.getShipName() + " ￥" + subscribePrice;
        }
        if (AgedmallShipDictConstant.SHIP_SN_SELF.equals(order.getDeliverySn())) {
            TempSubOrderParamDeliverySelf self = JSONObject.parseObject(order.getDeliveryChoose(), TempSubOrderParamDeliverySelf.class);
            String selfPrice = BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            if (null != self && null != self.getPrice()) {
                selfPrice = self.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            }
            result = shipTypeVo.getShipName() + " ￥" + selfPrice;
        }
        if (StringUtils.isNotEmpty(order.getUpfloor())) {
            TempSubOrderParamUpFloor upFloorService = JSONObject.parseObject(order.getUpfloor(), TempSubOrderParamUpFloor.class);
            if (null != upFloorService) {
                String desc = "";
                BigDecimal price = BigDecimal.ZERO;
                if (null != upFloorService.getPrice()) {
                    price = upFloorService.getPrice();
                }
                String priveStr = price.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
                desc = ("lift".equals(upFloorService.getType()) ? "全层电梯 " : "需要爬楼 ") + upFloorService.getLayer() + "楼 服务费：￥" + priveStr;
                result += " " + desc;
            }
        }

        return result;
    }

    public Object pickupDetail(Integer afterSaleId){
        BackendAfterSalePickupVo backendAfterSalePickupVo = backendAfterSaleMapper.pickupDetail(afterSaleId);
        backendAfterSalePickupVo.setOrderState(OrderUtil.backendShowType(backendAfterSalePickupVo.getOrderState().shortValue()));
        return ResponseUtil.ok(backendAfterSalePickupVo);
    }

    public Object pickup(Integer afterSaleId, Integer ship, Integer deliveryManId, String expressCompany, String expressCode){
        AgedmallReturnGoodsRecordExample example = new AgedmallReturnGoodsRecordExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andAfterSaleIdEqualTo(afterSaleId);
        AgedmallReturnGoodsRecord agedmallReturnGoodsRecord = agedmallReturnGoodsRecordMapper.selectOneByExample(example);
        if (null != agedmallReturnGoodsRecord) {
            agedmallReturnGoodsRecord.setUpdoorType(ship);
            agedmallReturnGoodsRecord.setDeliveryManId(deliveryManId);
            agedmallReturnGoodsRecord.setExpressName(expressCompany);
            agedmallReturnGoodsRecord.setExpressCode(expressCode);
            agedmallReturnGoodsRecordMapper.updateByPrimaryKeySelective(agedmallReturnGoodsRecord);
        }
        // 添加售后状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, afterSaleId, ProcessStateConstant.AFTERSALE_STATE_PICKUP);
        return ResponseUtil.ok();
    }

    public Object ship(Integer afterSaleId, Integer ship, Integer deliveryManId, String expressCompany, String expressCode, Integer shipPriceType){
        AgedmallReturnGoodsRecordExample example = new AgedmallReturnGoodsRecordExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andAfterSaleIdEqualTo(afterSaleId);
        AgedmallReturnGoodsRecord agedmallReturnGoodsRecord = agedmallReturnGoodsRecordMapper.selectOneByExample(example);
        if (null != agedmallReturnGoodsRecord) {
            agedmallReturnGoodsRecord.setSendType(ship);
            agedmallReturnGoodsRecord.setSendDeliveryManId(deliveryManId);
            agedmallReturnGoodsRecord.setSendExpressName(expressCompany);
            agedmallReturnGoodsRecord.setSendExpressCode(expressCode);
            agedmallReturnGoodsRecord.setSendPriceType(shipPriceType);
            agedmallReturnGoodsRecordMapper.updateByPrimaryKeySelective(agedmallReturnGoodsRecord);


            //添加打印凭条表
            AgedmallPrintOrder printOrder=new AgedmallPrintOrder();
            Integer orderGoodsId=Integer.parseInt(agedmallReturnGoodsRecord.getGoodsIds());
            SeparateWechatData storeMessageByOrderGoodsId = agedmallShopMapper.getStoreMessageByOrderGoodsId(orderGoodsId);
            printOrder.setType(0);
            printOrder.setIdType(1);
            printOrder.setBindingId(agedmallReturnGoodsRecord.getId().longValue());
            LitemallOrderItemExample orderExample =new LitemallOrderItemExample();
            orderExample.or().andChildOrderCodeEqualTo(agedmallReturnGoodsRecord.getOrderCode());
            LitemallOrderItem order=litemallOrderItemMapper.selectOneByExample(orderExample);
            LitemallOrder parentOrder = litemallOrderMapper.selectByPrimaryKey(order.getParentId());
            printOrder.setOrderSn(parentOrder.getOrderSn());
            printOrder.setIsPrint(0);
            printOrder.setState(0);
            printOrder.setAddTime(LocalDateTime.now());
            printOrder.setStoreId(storeMessageByOrderGoodsId.getStoreId());
            agedmallPrintOrderMapper.insertSelective(printOrder);
        }
        // 添加售后状态
        agedmallProcessStateService.addProcess(ProcessStateConstant.TYPE_AFTERSALE, afterSaleId, ProcessStateConstant.AFTERSALE_STATE_DELIVER);


        return ResponseUtil.ok();
    }


    public Object approved(Integer id){
        LitemallAftersale aftersale=litemallAftersaleMapper.selectByPrimaryKey(id);
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(aftersale.getOrderId());
        LitemallOrder bidOrder=litemallOrderMapper.selectByPrimaryKey(litemallOrderItem.getParentId());

        AgedmallReturnGoodsRecordExample returnGoodsRecordExample=new AgedmallReturnGoodsRecordExample();
        returnGoodsRecordExample.createCriteria().andAfterSaleIdEqualTo(id);
        AgedmallReturnGoodsRecord goodsRecord=agedmallReturnGoodsRecordMapper.selectOneByExample(returnGoodsRecordExample);

        aftersale.setHandleTime(LocalDateTime.now());
        //只退款
        if(aftersale.getType().equals(AftersaleConstant.TYPE_GOODS_MISS)){
            //TODO 进行退款操作
            Map<String,Object> refundData = new HashMap<>();
            refundData.put("afterSaleId", aftersale.getId());
            refundData.put("bigOrderCode", bidOrder.getOrderSn());
            refundData.put("price", aftersale.getAmount());
            directExchangeProducer.send(JacksonUtil.toJson(refundData),DirectExchangeRabbitMQConfig.QUEUE_WX_REFUND);
            return ResponseUtil.ok();
        }
        //退货退款
        else if(aftersale.getType().equals(AftersaleConstant.TYPE_GOODS_NEEDLESS)){
            //上门取件
            if(goodsRecord.getGetGoodsStyle()==0){

            }
            //送货到店
            else if(goodsRecord.getGetGoodsStyle()==1){
                aftersale.setStatus(AftersaleConstant.STATUS_WAIT_RECEIVE);
            }
            //自行寄回
            else if(goodsRecord.getGetGoodsStyle()==2){
                aftersale.setStatus(AftersaleConstant.STATUS_WAIT_RECEIVE);
            }
        }
        //换货
        else if(aftersale.getType().equals(AftersaleConstant.TYPE_GOODS_REQUIRED)){
            //上门取件
            if(goodsRecord.getGetGoodsStyle()==0){

            }
            //送货到店
            else if(goodsRecord.getGetGoodsStyle()==1){
                aftersale.setStatus(AftersaleConstant.STATUS_WAIT_RECEIVE);
            }
            //自行寄回
            else if(goodsRecord.getGetGoodsStyle()==2){
                aftersale.setStatus(AftersaleConstant.STATUS_WAIT_RECEIVE);
            }
        }

        litemallAftersaleMapper.updateByPrimaryKeySelective(aftersale);
        return ResponseUtil.ok();
    }


    public Object refused( AfterSaleRefusedVo afterSaleRefusedVo){
        LitemallAftersale aftersale=litemallAftersaleMapper.selectByPrimaryKey(afterSaleRefusedVo.getId());
        aftersale.setStatus(AftersaleConstant.STATUS_REJECT);
        aftersale.setRejectReason(afterSaleRefusedVo.getReason());
        litemallAftersaleMapper.updateByPrimaryKeySelective(aftersale);
        return ResponseUtil.ok();
    }

    public Object confirmGoods(Integer id){
        LitemallAftersale aftersale=litemallAftersaleMapper.selectByPrimaryKey(id);
        LitemallOrderItem litemallOrderItem = litemallOrderItemMapper.selectByPrimaryKey(aftersale.getOrderId());
        LitemallOrder bidOrder=litemallOrderMapper.selectByPrimaryKey(litemallOrderItem.getParentId());

        AgedmallReturnGoodsRecordExample returnGoodsRecordExample=new AgedmallReturnGoodsRecordExample();
        returnGoodsRecordExample.createCriteria().andAfterSaleIdEqualTo(id);
        AgedmallReturnGoodsRecord goodsRecord=agedmallReturnGoodsRecordMapper.selectOneByExample(returnGoodsRecordExample);

        aftersale.setHandleTime(LocalDateTime.now());
        //退货退款
        if(aftersale.getType().equals(AftersaleConstant.TYPE_GOODS_NEEDLESS)){
            Map<String,Object> refundData = new HashMap<>();
            refundData.put("afterSaleId", aftersale.getId());
            refundData.put("bigOrderCode", bidOrder.getOrderSn());
            refundData.put("price", aftersale.getAmount());
            directExchangeProducer.send(JacksonUtil.toJson(refundData),DirectExchangeRabbitMQConfig.QUEUE_WX_REFUND);
            goodsRecord.setEndTime(LocalDateTime.now());
            agedmallReturnGoodsRecordMapper.updateByExampleSelective(goodsRecord,returnGoodsRecordExample);
            return ResponseUtil.ok();
        }
        //换货
        else if(aftersale.getType().equals(AftersaleConstant.TYPE_GOODS_REQUIRED)){
            aftersale.setStatus(AftersaleConstant.STATUS_EXCHANGE);
            //这边进行换货发货操作
            //上门取件
            if(goodsRecord.getGetGoodsStyle()==0){

            }
            //送货到店
            else if(goodsRecord.getGetGoodsStyle()==1){
                aftersale.setStatus(AftersaleConstant.STATUS_FINISH);
            }
            //自行寄回
            else if(goodsRecord.getGetGoodsStyle()==2){
                List<Integer> orderGoodsList=new ArrayList<>();
                orderGoodsList.add(aftersale.getOrderGoodsId());
                LitemallOrderGoods orderGoods=litemallOrderGoodsMapper.selectByPrimaryKey(aftersale.getOrderGoodsId());
                aftersale.setStatus(AftersaleConstant.STATUS_WAIT_RECEIVE);
                AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
                agedmallLgBaseInfo.setOrderCode(bidOrder.getOrderSn()+"");
                agedmallLgBaseInfo.setLgType(LgBaseInfoLgType.EXCHANGE.getCode());
                agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsList,null));
                agedmallLgBaseInfo.setUserName(bidOrder.getConsignee());
                agedmallLgBaseInfo.setPhone(bidOrder.getMobile());
                agedmallLgBaseInfo.setAddresss(bidOrder.getAddress());
                agedmallLgBaseInfo.setWarehouseType(orderGoods.getStockType()==3? 1 : 0);
                Integer noticeType=0;
                if(orderGoods.getStockType()==3){
                    AgedmallCloudHouse cloudHouse=agedmallCloudHouseMapper.selectByPrimaryKey(orderGoods.getStoreId());
                    agedmallLgBaseInfo.setWarehouseAddress(cloudHouse.getAddressDetail());
                    agedmallLgBaseInfo.setStoreId(cloudHouse.getId());
                    noticeType=2;
                }
                else {
                    AgedmallStore store=agedmallStoreMapper.selectByPrimaryKey(orderGoods.getStoreId().longValue());
                    agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
                    agedmallLgBaseInfo.setStoreId(store.getId().intValue());
                    AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreIdAndType(store.getId().intValue(),0);
                    if(store.getDeliveryMode()==2&&null != announcerBaseInfo){
                        noticeType=2;
                    }
                    else{
                        noticeType=1;
                    }
                }
                agedmallLgBaseInfo.setNoticeType(noticeType);
                agedmallLgBaseInfo.setLgStat(LgBaseInfoStatConstant.CHANGE_UN_SENDING);
                agedmallLgBaseInfo.setLgIsOver(0);
                agedmallLgBaseInfoMapper.insertSelective(agedmallLgBaseInfo);
                aftersale.setBaseInfoId(agedmallLgBaseInfo.getId());
                List<Integer> missionList = logisticBusiBaseServiceImpl.createMission(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode());
                //发送企业微信通知
                ToLitemallBean toLitemallBean = new ToLitemallBean();
                toLitemallBean.setType(ReceiveOrderResultTypeEum.SENDNOTICE.getCode());
                toLitemallBean.setMissionId(missionList);
                directExchangeProducer.send(JSONUtil.toJsonStr(toLitemallBean), DirectExchangeRabbitMQConfig.TO_LITEMALL_NOTICE);
            }
        }

        litemallAftersaleMapper.updateByPrimaryKeySelective(aftersale);
        return ResponseUtil.ok();
    }

}
